package com.citcc.api.controller;

import com.citcc.api.filter.JwtUtil;
import com.citcc.business.bean.CdzAppUser;
import com.citcc.business.bean.CdzPush;
import com.citcc.business.service.CdzAppUserService;
import com.citcc.business.service.CdzPushService;
import com.citcc.common.base.AjaxResult;
import com.citcc.common.jpush.PushUtil;
import com.citcc.common.utils.StringUtils;
import com.citcc.framework.base.BaseController;
import com.citcc.framework.sms.MessageUtil;
import com.citcc.framework.sms.SMSTemplateCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Api(tags = "app用户账号相关")
@RestController
@RequestMapping("/user")
public class AppUserController extends BaseController {

    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    @Autowired
    private JwtUtil jwtUtil;

    private final CdzAppUserService cdzAppUserService;

    private CdzPushService cdzPushService;

    @Autowired
    public AppUserController(CdzAppUserService cdzAppUserService,CdzPushService cdzPushService) {
        this.cdzAppUserService = cdzAppUserService;
        this.cdzPushService = cdzPushService;
    }

    @ApiOperation("APP用户注册")
    @PostMapping("/v2/register")
    public AjaxResult userRegister(CdzAppUser cdzAppUser) {
        String msg = cdzAppUserService.userRegister(cdzAppUser);
        if (msg == null) {
            return success(200);
        } else {
            return error(-1, msg);
        }
    }

    @ApiOperation("APP用户重置密码")
    @PostMapping("/v2/reset")
    public AjaxResult userReset(CdzAppUser cdzAppUser) {
        String msg = cdzAppUserService.userReset(cdzAppUser);
        if (msg == null) {
            return success(200);
        } else {
            return error(-1, msg);
        }
    }

    @PostMapping("/v2/login")
    @ApiOperation(value = "APP用户登录", notes = "微信快捷登录、支付宝快捷登录需传入对应的openId")
    public AjaxResult userLogin(CdzAppUser cdzAppUser) {

        String wechatOpenid = cdzAppUser.getWechatOpenid();
        String alipayOpenid = cdzAppUser.getAlipayOpenid();

        if (StringUtils.isNotBlank(wechatOpenid)) {
            // 微信快捷登录
            CdzAppUser user = cdzAppUserService.getAppUserByOpenId(wechatOpenid, null);
            if (user == null) return error("微信快捷登录失败");
            cdzAppUser.setPhone(user.getPhone());
        } else if (StringUtils.isNotBlank(alipayOpenid)) {
            // 支付宝快捷登录
            CdzAppUser user = cdzAppUserService.getAppUserByOpenId(null, alipayOpenid);
            if (user == null) return error("支付宝快捷登录失败");
            cdzAppUser.setPhone(user.getPhone());
        } else {
            // 账号密码登录
            String msg = cdzAppUserService.userLogin(cdzAppUser);
            if (StringUtils.isNotBlank(msg)) return error(msg);
        }
        // 校验用户信息成功，生成token值
        String jwt = jwtUtil.generateToken(cdzAppUser.getPhone());
        HashMap<String, String> token = new HashMap<String, String>() {{
            put("token", jwt);
        }};
        return success(200, token);
    }

    @ApiOperation("手机验证码发送")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1:注册，2:重置密码", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "1:注册，2:重置密码", paramType = "query")
    })
    @GetMapping("/v2/code")
    public AjaxResult userCode(@RequestParam String phone, @RequestParam int type) {
        String templateCode;
        switch (type) {
            case 1:
                templateCode = SMSTemplateCode.REGISTER.getTemplateCode();
                break;
            case 2:
                templateCode = SMSTemplateCode.RESET.getTemplateCode();
                break;
            default:
                templateCode = SMSTemplateCode.LOGIN.getTemplateCode();
        }
        Random rand = new Random();
        String code = String.valueOf(rand.nextInt(899999) + 100000);
        MessageUtil.smsCode(phone, code, templateCode);
        System.setProperty(phone, code);
        cachedThreadPool.execute(() -> {
            try {
                Thread.sleep(1000 * 60 * 2);
                System.setProperty(phone, "");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        return success(200);
    }

    @ApiOperation("批量给用户发送通知（内部调用）")
    @PostMapping("/v2/notification")
    public AjaxResult notification() {
        CdzAppUser appUser = new CdzAppUser();
        appUser.setDateTime("2019-05-27");
        List<CdzAppUser> list = cdzAppUserService.selectAllList(appUser);
        if (null != list && list.size() > 0){
            List<Object> registrationIdList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CdzAppUser user = list.get(i);
                if (StringUtils.isNotBlank(user.getDeviceId())){
                    registrationIdList.add(user.getDeviceId());
                    String title = "通知公告";
                    String body = "因个别用户登录信息失效造成充电失败的情况，重新登录app即可解决。绿能充app今晚八点会重新发版，杜绝此问题再次产生。给您造成的不便，敬请谅解，期待您再次使用绿能充！";
                    String url = "/h5/chargingPile/notice.html";
                    try {
                        PushUtil.msgPush(registrationIdList, title, body, "1",url,user.getType());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //插入推送数据
                    CdzPush push = new CdzPush();
                    push.setTitle(title);
                    push.setContent(body);
                    push.setUrl(url);
                    push.setUserId(user.getId());
                    push.setPushTime(new Date());
                    cdzPushService.save(push);
                }
            }
        }else{
            return error(-1, "未查到用户集合");
        }
        return success(200);
    }
}


